package com.hkrt.util;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.processors.FlowableProcessor;
import io.reactivex.processors.PublishProcessor;

/**
 *  @author 陈金广
 * @date 2017/12/1
 *
 * 使用方法：
 *  发送事件
 *  RxBus.getInstance().post("111");
 *  注册事件
 *  Flowable<String> f = RxBus.getInstance().register(String.class);
 *  f.subscribe(new Consumer<String>() {
 *      @Override
 *      public void accept(String integer) throws Exception {
 *          toast(integer);
 *      }
 *  });
 *  解除注册
 *  @Override
 *   public void onDestroy() {
 *      super.onDestroy();
 *      RxBus.getInstance().unregisterAll();
 *   }
 *
 *
 */
public class RxBus {
    private final FlowableProcessor<Object> mBus;

    private RxBus() {
        mBus = PublishProcessor.create().toSerialized();
    }

    private static class Holder {
        private static RxBus instance = new RxBus();
    }

    public static RxBus getInstance() {
        return Holder.instance;
    }

    public void post(@NonNull Object obj) {
        mBus.onNext(obj);
    }

    public <T> Flowable<T> register(Class<T> clz) {
        return mBus.ofType(clz);
    }

    public void unregisterAll() {
        //解除注册
        mBus.onComplete();
    }

    public boolean hasSubscribers() {
        return mBus.hasSubscribers();
    }
}